package com.xyl.controller;

import com.xyl.service.FileUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class FileController {

    @Autowired
    private FileUploadService uploadService;

    @RequestMapping("/file_upload.action")
    public String visitFile(){

        return "upload_file";
    }

    @RequestMapping("/save_upload.action")
    public String saveFile(HttpServletRequest request, MultipartFile file){
        // 通过请求对象获得application全局内置对象，通过application全局对象获取应用在服务器部署的物理路径
        HttpSession session = request.getSession();
        ServletContext application = session.getServletContext();
        String realPath = application.getRealPath("/");
        realPath =realPath.replace("\\","/")+"files/";
        if(file != null){
            String fileName = file.getOriginalFilename();
        //     获得文件类型
            String type = fileName.substring(fileName.lastIndexOf(".")+1);
            String newName = dealTime()+ UUID.randomUUID()+type;
            File saveFile = new File(realPath+newName);
            try {
                file.transferTo(saveFile);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //存储数据
            Map<String ,String> map = new HashMap<>();
            map.put("name",fileName);
            map.put("path","/files/"+newName);
            uploadService.saveFile(map);

        }
        return "redirect:upload_list.action";
    }

    @RequestMapping("/upload_list.action")
    public String queryList(Model model){
        List<Map<String,String>> list = uploadService.queryList();
        model.addAttribute("filelist",list);
        return "upload_file";
    }

    private String dealTime(){
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }


}
